<?php


namespace App\Libs\Qiniu;


use App\Api\Sport\Models\Photos;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;

class QiniuService
{
    public static function lists ()
    {
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $auth = new Auth($accessKey,$secretKey);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $bucket = 'wq113';
        $prefix = '';
        $marker = \Cache::get('qiniu_marker');
        $limit = 500;
        $delimiter = '/';
        // 列举文件
        list($res, $err) = $bucketManager->listFiles($bucket, $prefix, $marker, $limit, $delimiter);
        info('七牛列举文件', [$res, $err]);
        if($err !== null || empty($res['items'])) exit;
        \Cache::put('qiniu_marker',$res['marker'], 10);
        $photosKey = array_column($res['items'],'key');
        $photos = Photos::whereIn('local_name',$photosKey)->pluck('local_name')->toArray();
        $diff = array_diff($photosKey,array_unique($photos));
        if($diff)self::changeType($diff);
    }

    public static function changeType($fileKey)
    {
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $auth = new Auth($accessKey,$secretKey);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $bucket = 'wq113';
        $keyTypePairs = [];
        //type=0表示普通存储，type=1表示低频存储
        foreach ($fileKey as $key) {
            $keyTypePairs[$key] = 1;
        }
        $ops = $bucketManager->buildBatchChangeType($bucket, $keyTypePairs);
        list($ret, $err) = $bucketManager->batch($ops);
        info('七牛更新文件存储类型',[$fileKey, $ret, $err]);
    }


}